package com.platform.service.impl;

import com.platform.common.logger.annotation.EnableLogger;
import com.platform.common.util.DateUtil;
import com.platform.common.util.StringUtil;
import com.platform.dao.UserAuthorizationDao;
import com.platform.dao.UserDao;
import com.platform.domain.model.User;
import com.platform.domain.model.UserAuthorization;
import com.platform.domain.model.UserAuthorizationKey;
import com.platform.service.UserService;
import com.platform.service.common.Constants;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * User
 * <p/>
 * User: wangyang
 * DateTime: 2012-10-08 16:11:58
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @EnableLogger
    private Logger logger;

    @Resource
    private UserDao userDao;

    @Resource
    private UserAuthorizationDao userAuthorizationDao;

    /**
     * 根据登录名查询用户
     *
     * @param loginId 登录ID
     * @return 用户对象
     * @throws Exception
     */
    @Override
    public User selectByLoginId(String loginId) throws Exception {
        return userDao.selectByLoginId(loginId);
    }

    /**
     * 根据用户对象条件查询符合条件的用户对象集合
     *
     * @param user 用户对象
     * @return 用户对象集合
     * @throws Exception
     */
    @Override
    public List<User> selectList(User user) throws Exception {
        if (user == null) {
            user = new User();
        }
        user.setDeltag(Constants.IS_FALSE);
        return userDao.selectList(user);
    }

    /**
     * 根据用户对象条件查询符合条件的用户记录总条数
     *
     * @param user 用户对象
     * @return 记录总条数
     * @throws Exception
     */
    @Override
    public int selectListCount(User user) throws Exception {
        return userDao.selectListCount(user);
    }

    /**
     * 根据主键查询User对象
     *
     * @param userId
     * @return User对象
     */
    @Override
    public User selectByPrimaryKey(String userId) throws Exception {
        return userDao.selectByPrimaryKey(userId);
    }

    /**
     * 根据查询条件查询符合条件的User对象
     *
     * @param user
     * @return 符合条件的User对象List
     */
    @Override
    public List<User> select(User user) throws Exception {
        return userDao.select(user);
    }

    /**
     * 根据主键删除User对象
     *
     * @param userId
     * @return 影响条件数
     */
    @Override
    public int deleteByPrimaryKey(String userId) throws Exception {
        return userDao.deleteByPrimaryKey(userId);
    }

    /**
     *
     * 根据主键逻辑删除User对象
     *
     * @param userId
     * @return 影响条件数
     */
    public int delete(String userId) throws Exception {
        User user = this.selectByPrimaryKey(userId);
        user.setDeleteTime(DateUtil.toDayString(DateUtil.YYYY_MM_DD_24H_MM_SS));
        user.setDeltag(Constants.IS_TRUE);
        return userDao.update(user);
    }

    /**
     * 根据条件删除符合条件的User对象
     *
     * @param user
     * @return 影响条件数
     */
    @Override
    public int delete(User user) throws Exception {
        return userDao.delete(user);
    }

    /**
     * 插入User对象
     *
     * @param user
     * @return 影响条件数
     */
    @Override
    public int insert(User user) throws Exception {
        return userDao.insert(user);
    }

    /**
     * 更新User对象
     *
     * @param user
     * @return 影响条件数
     */
    @Override
    public int update(User user) throws Exception {
        if (user.getRoleId() != null && StringUtil.isNotBlank(user.getRoleId())) {
            UserAuthorization userAuth = new UserAuthorization();
            // 查询用户当前的默认角色
            userAuth.setUserId(user.getUserId());
            userAuth.setDefaultRoleSign(Constants.IS_TRUE);
            List<UserAuthorization> list = userAuthorizationDao.select(userAuth);
            UserAuthorization userAuth_before = null;
            if (list != null && list.size() == 1) {
                userAuth_before = list.get(0);
            }

            if (userAuth_before != null && !userAuth_before.getRoleId().equals(user.getRoleId())) {
                // 将角色置为非默认角色
                userAuth_before.setDefaultRoleSign(Constants.IS_FALSE);
                // 保存用户角色
                userAuthorizationDao.update(userAuth_before);
            }

            if (userAuth_before == null || !userAuth_before.getRoleId().equals(user.getRoleId())) {
                // 查询待更新的角色
                UserAuthorizationKey userAuthKey = new UserAuthorizationKey();
                userAuthKey.setUserId(user.getUserId());
                userAuthKey.setRoleId(user.getRoleId());
                userAuth = userAuthorizationDao.selectByPrimaryKey(userAuthKey);
                // 将角色置为默认角色
                userAuth.setDefaultRoleSign(Constants.IS_TRUE);
                // 保存用户默认角色
                userAuthorizationDao.update(userAuth);
            }
        }
        return userDao.update(user);
    }

    /**
     * 插入UserAuthorization对象
     *
     * @param user 信息
     * @return 影响条件数
     */
    @Override
    public int insertUserAuthorizations(User user) throws Exception {
        String userId = user.getUserId();
        UserAuthorization userAuth = new UserAuthorization();
        // 查询用户当前的默认角色
        userAuth.setUserId(userId);
        userAuth.setDefaultRoleSign(Constants.IS_TRUE);
        List<UserAuthorization> list = userAuthorizationDao.select(userAuth);
        UserAuthorization userAuth_before = null;
        if (list != null && list.size() == 1) {
            userAuth_before = list.get(0);
        }
        // 删除用户当前的授权信息
        userAuth = new UserAuthorization();
        userAuth.setUserId(userId);
        userAuthorizationDao.delete(userAuth);
        // 插入新的授权信息
        int i = 0;
        boolean bool_defaultRole = false;
        String roleIds = user.getRoleId();
        logger.info("insertUserAuthorizations info: " + userId + ' ' + roleIds);
        String[] roleIdArray = roleIds.split(Constants.SEPARATOR);
        for (String roleId : roleIdArray) {
            userAuth = new UserAuthorization();
            userAuth.setUserId(userId);
            userAuth.setRoleId(roleId);
            userAuth.setCreateTime(DateUtil.toDayString(DateUtil.YYYY_MM_DD_24H_MM_SS));
            // 判断是否是用户的默认角色
            if (!bool_defaultRole
                    && userAuth_before != null
                    && userAuth.getRoleId().equals(userAuth_before.getRoleId())) {
                userAuth.setDefaultRoleSign(Constants.IS_TRUE);
                bool_defaultRole = true;
            } else {
                userAuth.setDefaultRoleSign(Constants.IS_FALSE);
            }
            i += userAuthorizationDao.insert(userAuth);
        }
        return i;
    }
}
